package cn.wecloud.im.multiplayervideodemo.utils

import android.annotation.SuppressLint
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import cn.wecloud.im.multiplayervideodemo.App
import cn.wecloud.im.multiplayervideodemo.R


@SuppressLint("StaticFieldLeak")
object SoundPlayUtils {
    // SoundPool对象
    private var mSoundPlayer: SoundPool? = null
        get() {
            if (field == null) {
                field = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    SoundPool.Builder().setMaxStreams(10).build()
                } else {
                    SoundPool(10, AudioManager.STREAM_MUSIC, 1)
                }
            }
            return field
        }


    fun play(resId: Int = R.raw.message, looper: Boolean? = false) {
        release()
        val soundId = mSoundPlayer?.load(App.instance, resId, 1)
        mSoundPlayer?.setOnLoadCompleteListener { soundPool, _, _ ->
            soundPool?.play(
                    soundId ?: 0,
                    1F,
                    1F,
                    1,
                    if (looper == true) {
                        -1
                    } else {
                        0
                    },
                    1F
            )
        }
    }

    /**
     * 播放消息声音
     */
    fun messagePlay() {
        play()
    }

    /**
     * 挂断
     */
    fun handUpPlay() {
        play(R.raw.ic_hang_up)
    }

    /**
     * 通话声音
     */
    fun incomingTelegram() {
        play(R.raw.ic_incoming_telegram, true)
    }

    fun outgoingCall() {
        play(R.raw.outgoing_call_ring, true)
    }


    fun stopPlay() {
        release()
    }


    /**
     * 释放资源
     */
    fun release() {
        mSoundPlayer?.release()
        mSoundPlayer = null
    }


}
